/**
 * 发送短信验证码
 */
;(function ($) {
    'use strict';

    function SendCode (element, options) {
        options = options || {};
        options.resetStr = $(element).html();

        this.$btn = $(element);
        this.options = $.extend({}, SendCode.DEFAULTS, options);
    }

    SendCode.DEFAULTS = {
        second: 60,                 // 倒计时时长（秒）
        disClass: 'disabled',       // 禁用按钮样式
        runStr: '重新发送({%s})',   // 倒计时显示文本
        resetStr: '发送验证码'      // 倒计时结束后按钮显示文本
    };

    SendCode.timer = null;

    /**
     * 开始倒计时
     */
    SendCode.prototype.start = function () {
        var $this = this,
            options = $this.options,
            second = options.second;

        //- pointer-events: 禁用鼠标事件
        $this.$btn.html($this.getStr(second)).css('pointer-events', 'none').addClass(options.disClass);

        $this.timer = setInterval(function () {
            second--;
            $this.$btn.html($this.getStr(second));
            if (second <= 0) {
                $this.resetBtn();
                clearInterval($this.timer);
            }
        }, 1000);
    };

    /**
     * 获取倒计时显示文本
     * @param second
     * @returns {string}
     */
    SendCode.prototype.getStr = function (second) {
        return this.options.runStr.replace(/\{([^{]*?)%s(.*?)\}/g, second);
    };

    /**
     * 重置按钮
     */
    SendCode.prototype.resetBtn = function () {
        var $this = this,
            options = $this.options;

        $this.$btn.html(options.resetStr).css('pointer-events', 'auto').removeClass(options.disClass);
    };

    function Plugin (option) {
        var sendcode = new SendCode(this, option);
        sendcode.start();
    }

    $.fn.countdown = Plugin;

})($);